/*
 * @Descripttion: 组件业务名
 * @version:
 * @Author: lhl
 * @Date: 2024-09-15 03:23:32
 * @LastEditors: lhl
 * @LastEditTime: 2024-09-17 20:22:58
 */
import { defineStore } from 'pinia';
import router, { resetRouter } from '@/router';
import API from '@/api';

interface UserState {
  /** 用户ID */
  userId?: number;
  /** 用户名 */
  username?: string;
  /** 昵称 */
  nickname?: string;
  /** 头像URL */
  avatar?: string;
  /** 角色 */
  roles: string[];
  /** 权限 */
  perms: string[];
}

export interface FormData {
  username: string;
  password: string;
  code: string;
  remember: boolean;
}

export const useUserInfo = defineStore('userInfo', {
  // 相当于data
  state: (): UserState => ({
    roles: [],
    perms: []
  }),
  actions: {
    /**
     * 登录
     */
    login(data: FormData): any {
      return new Promise((resolve, reject) => {
        API.login
          .loginApi(data)
          .then((response) => {
            const { token } = response.data;
            localStorage.setItem('authToken', token);
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    getUserInfo() {
      return new Promise((resolve, reject) => {
        API.system
          .uerInfoApi({})
          .then((response) => {
            if (!response.data) {
              reject('Verification failed, please Login again.');
              return;
            }
            if (!response.data.roles || response.data.roles.length <= 0) {
              reject('getUserInfo: roles must be a non-null array!');
              return;
            }
            Object.assign(this.$state, { ...response.data });
            resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    /**
     *  注销/登出
     */
    logout() {
      return new Promise((resolve, reject) => {
        API.login
          .logoOutApi({})
          .then((response) => {
            localStorage.clear();
            sessionStorage.clear();
            // 刷新页面
            // location.reload();
            // 重置路由
            resetRouter();
            router.push('/login');
            resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    /**
     * 清除 Token
     */
    resetToken() {
      return new Promise((resolve) => {
        localStorage.removeItem('token');
        resolve(null);
      });
    }
  },

  // 配合pinia-plugin-persist插件 持久化 默认存储到 sessionStorage ，key 为 store 的 id
  persist: {
    enabled: true,
    strategies: [
      // 要持久化的状态字段 'roles', 'perms' 不需要缓存
      { storage: localStorage, paths: ['token', 'username', 'avatar'] }
    ]
  }
});
